package src;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;


public class ParticipantsDialog extends JDialog {
	private List<String> participants;
	private JTextField participantsField;
	
	public ParticipantsDialog(List<String> participants, JFrame frame) {
		this.setParticipants(participants);
		setAttributes(frame);
		addComponents();
		pack();
		loadParticipants();
	}

	private void setAttributes(JFrame frame) {
		setTitle("Fill Participants");
		setModalityType(ModalityType.APPLICATION_MODAL);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setLocationRelativeTo(frame);
	}

	private void loadParticipants() {
		if (getParticipants() != null) {
			getParticipantsField().setText(mountParticipantsString(getParticipants()));
		}
	}

	private String mountParticipantsString(List<String> names) {
		StringBuilder allNames = new StringBuilder();
		for (String name : names) {
			if (allNames.length() != 0) {
				allNames.append(", ");
			}
			allNames.append(name);
		}
		return allNames.toString();
	}

	private void addComponents() {
		setLayout(new FlowLayout());
		add(getParticipantsLabel());
		add(getParticipantsField());
		add(getOkButton());
	}

	private JButton getOkButton() {
		JButton button = new JButton("OK");
		
		button.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String[] items = getParticipantsField().getText().split(" *, *");
				
				ParticipantsDialog.this.getParticipants().clear();
				ParticipantsDialog.this.getParticipants().addAll(Arrays.asList(items));
				ParticipantsDialog.this.dispose();
				
			}

		});
		
		return button;
	}
	
	private JLabel getParticipantsLabel() {
		return new JLabel("Participants: ");
	}

	private JTextField getParticipantsField() {
		if (participantsField == null) {
			participantsField = new JTextField(30);
		}
		return participantsField;
	}

	public List<String> selectParticipants() {
		setVisible(true);
		return participants;
	}

	void setParticipants(List<String> participants) {
		this.participants = participants;
	}

	List<String> getParticipants() {
		if (participants == null) {
			participants = new ArrayList<String>();
		}
		return participants;
	}
}
